package cn.wolfcode.luowowo.website.resolver;


import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.GettokenUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户对象参数解析器
 *
 * 实现的功能:
 *   将当前登录的用户对象, 以形式参数个格式注入到请求映射方法中
 *  @RequestMapping("/useInfo")
 *  public Object useInfo(UserInfo userInfo){
 *     //userInfo 就是当前登录用户对象
 *  }
 */
public class UserInfoArgumentResolver  implements HandlerMethodArgumentResolver {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //明确需要注入参数对象的类型
    //如果为true, 表示支持该类型, 如果为false表示不支持该类型注入
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //parameter.getParameterType() 映射方法形式参数类型
        //== UserInfo.class  表示当前参数解析器仅仅支持对UserInfo.class类型注入
        return parameter.getParameterType() == UserInfo.class
                && parameter.hasParameterAnnotation(UserParam.class);  //判断有没有贴有这个注解
    }
    //UserInfo userInfo 形式参数实例注入逻辑
    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        //获取当前请求对象
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String  token = GettokenUtil.getUser(request);
        UserInfo userInfo = userInfoRedisService.gettoken(token);
        return userInfo;
    }
}
